package com.huifaapp.mall.activity;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.SPUtils;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.huifaapp.mall.R;
import com.huifaapp.mall.activity.Homefragment.HelpcenterActivity;
import com.huifaapp.mall.activity.Homefragment.MessageActivity;
import com.huifaapp.mall.activity.Homefragment.OneShareActivity;
import com.huifaapp.mall.activity.Homefragment.ReturnafterActivity;
import com.huifaapp.mall.afinal.SPConstants;
import com.huifaapp.mall.api.ApiManager;
import com.huifaapp.mall.bean.MineFragmentBean;
import com.huifaapp.mall.uitils.AUniqueIdentifier;
import com.huifaapp.mall.uitils.BlurBitmapUtil;
import com.huifaapp.mall.view.RoundImageView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.squareup.okhttp.Request;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;


/**
 * Created by Administrator on 2017-11-27.
 */

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class MineFragment extends Fragment {
    private LinearLayout Longing;
    private ImageView ImageSet;
    private LinearLayout LinearHelpCenter;
    private LinearLayout LinearMyRedBag;
    private LinearLayout ll_mine_myCollect;
    private LinearLayout LinearComplaint;
    private TextView Immediatecash;
    private LinearLayout LinearMyOrder;
    //红包
    private ImageView imgRed;
    //退货收货
    private ImageView imagereturnafter;
    //待付款
    private ImageView ImaPending;
    //待发货
    private ImageView ImaLivery;
    //待收货
    private ImageView ImaGoodreceive;
    //待评论
    private ImageView ImaPendcomm, userImageBg;
    private TextView TvTotalprofit,TvPreprofit,Tvorder,Tvviplevel,Tvmoney,TvuserNickname,TvJifen,TvCollection,TvShoppingCart;
    private MineFragmentBean.UserinfoBean userinfolist;
    private ImageView ImHeadset;
    private MineFragmentBean.StoreBean storelist;
    //我的收藏
    private TextView mycollection;
    private RoundImageView roundImageView;
    //客服
    private ImageView im_kefu;
    //投诉建议
    private ImageView im_tousu;
    //分享app
    private ImageView im_fxapp;

    //BANG
    private ImageView im_help;

    DisplayImageOptions options;
    private TextView fragment_mine_gwnum;
    private ImageView iv_fragment_mine_yaoqing;


    private LinearLayout ll_jinbi,ll_yumoney;
    private TextView tv_zhanghuyue;
    private  TextView  textView7;
//    private LinearLayout ll_jinbi;
//    private LinearLayout ll_yumoney;
//    private TextView tv_zhanghuyue;

    private ImageView iv_message_min;
    private TextView mess_yuan;
    private TextView dianpushuliang;
    private TextView fragment_mine_username;
    private RelativeLayout rl_setmessage;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View viewLayout = inflater.inflate(R.layout.fragment_mine, container, false);
        initView(viewLayout);

        //Glide.with(getActivity()).load(userinfolist)
        return viewLayout;
    }



    @Override
    public void onResume() {
        super.onResume();

        boolean login = isLogin(getActivity(), false);
        if (!login){
            //this is unlogin
            TvuserNickname.setText("登录/注册");
            rl_setmessage.setVisibility(View.GONE);
            mess_yuan.setVisibility(View.GONE);
            roundImageView.setImageResource(R.drawable.morentouxiang);
            ll_jinbi.setVisibility(View.GONE);
            ll_yumoney.setVisibility(View.GONE);
            tv_zhanghuyue.setVisibility(View.GONE);
//            Tvviplevel.setVisibility(View.GONE);
            Immediatecash.setVisibility(View.GONE);
            userImageBg.setImageResource(R.drawable.perbeijing);
            TvCollection.setText("0");
            TvShoppingCart.setText("0");
            dianpushuliang.setText("0");
//            TvuserNickname.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//
//                    Intent intent = new Intent(getActivity(), LoginActivity.class);
//                    startActivity(intent);
//                }
//            });

        }else if (login){
            ll_jinbi.setVisibility(View.VISIBLE);
            ll_yumoney.setVisibility(View.VISIBLE);
            tv_zhanghuyue.setVisibility(View.VISIBLE);
//            Tvviplevel.setVisibility(View.VISIBLE);
            Immediatecash.setVisibility(View.VISIBLE);
            rl_setmessage.setVisibility(View.VISIBLE);
        }
//        if (login){
//            TvuserNickname.setText("登录／注册");
////            roundImageView.setImageResource(R.drawable.morentouxiang);
//        }
//        ll_jinbi.setVisibility(View.VISIBLE);
//        ll_yumoney.setVisibility(View.VISIBLE);
        Log.e("个人中心url------",ApiManager.BASE_NIUPAI_URL+"users/index"+"?token"+SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN)+"&appId="+AUniqueIdentifier.getDeviceId(getActivity()));
        OkHttpUtils.get().url(ApiManager.BASE_NIUPAI_URL+"users/index")
                //token=201712291124171334f3ed61d93e05404b8dc78f10c4770cf8&appId=D7B72681-8205-4C8F-8CCB-142C448203E3")
                .addParams("token", SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN))
                .addParams("appId", AUniqueIdentifier.getDeviceId(getActivity()))
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Request request, Exception e) {

                    }

                    @Override
                    public void onResponse(String response) {
                        try {
                            Gson gson = new Gson();
                            MineFragmentBean mineFragmentBean = gson.fromJson(response, MineFragmentBean.class);
                            if (mineFragmentBean.getCode().equals("10000")) {
                                userinfolist = mineFragmentBean.getUserinfo();
                                changeLight(userImageBg, -60);
                                Glide.with(MineFragment.this).load(userinfolist.getUserHeadimg())
                                        .asBitmap()
                                        .into(roundImageView);
                                ImageLoader.getInstance().loadImage(userinfolist.getUserHeadimg(), new ImageLoadingListener() {
                                    @Override
                                    public void onLoadingStarted(String imageUri, View view) {
                                    }

                                    @Override
                                    public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                                    }

                                    @Override
                                    public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                                        userImageBg.setImageBitmap(BlurBitmapUtil.blurBitmap(getActivity(), loadedImage, 2));
                                    }

                                    @Override
                                    public void onLoadingCancelled(String imageUri, View view) {
                                    }
                                });
                                TvJifen.setText(mineFragmentBean.getUserinfo().getJifeng() + "惠金币");
                                Tvmoney.setText(mineFragmentBean.getUserinfo().getMoney() + "");
                                //  Tvviplevel.setText("VIP"+mineFragmentBean.getUserinfo().getVipLevel());
                                TvuserNickname.setText(mineFragmentBean.getUserinfo().getUserNickname());
                                TvCollection.setText(mineFragmentBean.getUserinfo().getCollection() + "");
                                TvShoppingCart.setText(mineFragmentBean.getUserinfo().getShoppingCart() + "");
                                if (mineFragmentBean.getUserinfo().getNotReadCount() == 0) {
                                    mess_yuan.setVisibility(View.GONE);
                                } else {
                                    mess_yuan.setVisibility(View.VISIBLE);
                                }

                                if (SPUtils.getInstance().getString(SPConstants.KEY_ISSTORE).equals("1")) {
                                    dianpushuliang.setText("1");
                                } else {
                                    dianpushuliang.setText("0");
                                }
//                          TvTotalprofit.setText(mineFragmentBean.getStore().getTotalProfit()+"");
//                          TvPreprofit.setText(mineFragmentBean.getStore().getPreProfit()+"");
//                          Tvorder.setText(mineFragmentBean.getStore().getOrder()+"");
                            }else if(mineFragmentBean.getCode().equals("10001")){
                                TvuserNickname.setText("登录/注册");
                                roundImageView.setImageResource(R.drawable.morentouxiang);
                                rl_setmessage.setVisibility(View.GONE);
                                ll_jinbi.setVisibility(View.GONE);
                                ll_yumoney.setVisibility(View.GONE);
                                tv_zhanghuyue.setVisibility(View.GONE);
                                mess_yuan.setVisibility(View.GONE);
//                              Tvviplevel.setVisibility(View.GONE);
                                Immediatecash.setVisibility(View.GONE);
                                userImageBg.setImageResource(R.drawable.perbeijing);
                                TvCollection.setText("0");
                                TvShoppingCart.setText("0");
                                dianpushuliang.setText("0");
//                                TvuserNickname.setOnClickListener(new View.OnClickListener() {
//                                    @Override
//                                    public void onClick(View v) {
//                                        Intent intent = new Intent(getActivity(), LoginActivity.class);
//                                        startActivity(intent);
//                                        }
//                                    });
                                }
                            }catch(Exception e){
                                e.printStackTrace();
                            }


                        }
                });


    }

    private void initView(View viewLayout) {
        Longing = (LinearLayout) viewLayout.findViewById(R.id.Longing);
        mess_yuan = (TextView) viewLayout.findViewById(R.id.mine_yuanyuan);
        mess_yuan.setVisibility(View.GONE);
        tv_zhanghuyue = (TextView) viewLayout.findViewById(R.id.mine_zhanghuyue);
        ll_jinbi = (LinearLayout) viewLayout.findViewById(R.id.mine_lljinbi);
        ll_yumoney = (LinearLayout) viewLayout.findViewById(R.id.mine_llyue);
        ImageSet = (ImageView) viewLayout.findViewById(R.id.ImageSet);
        Immediatecash = (TextView) viewLayout.findViewById(R.id.diatecash);
        roundImageView = (RoundImageView) viewLayout.findViewById(R.id.fragment_mine_Imheadset);
        LinearMyOrder = (LinearLayout) viewLayout.findViewById(R.id.myorder);
        ImaPending = (ImageView) viewLayout.findViewById(R.id.imagepending);
        ImaLivery = (ImageView) viewLayout.findViewById(R.id.imagedelivery);
        ImaGoodreceive = (ImageView) viewLayout.findViewById(R.id.imagegoodsrece);
        ImaPendcomm = (ImageView) viewLayout.findViewById(R.id.imagepedingcomm);
        imagereturnafter = (ImageView) viewLayout.findViewById(R.id.imagereturnafter);
        TvTotalprofit = (TextView) viewLayout.findViewById(R.id.fragment_mine_totalprofit);
        TvPreprofit = (TextView) viewLayout.findViewById(R.id.fragment_mine_preprofit);
        Tvorder = (TextView) viewLayout.findViewById(R.id.fragment_mine_order);
        TvuserNickname = (TextView) viewLayout.findViewById(R.id.fragment_mine_username);
      //  Tvviplevel = (TextView) viewLayout.findViewById(R.id.fragment_mine_viplevel);
        Tvmoney = (TextView) viewLayout.findViewById(R.id.fragment_mine_money);
        TvJifen = (TextView) viewLayout.findViewById(R.id.fragment_mine_jifen);
        TvCollection = (TextView) viewLayout.findViewById(R.id.fragment_mine_scnum);
        TvShoppingCart = (TextView) viewLayout.findViewById(R.id.fragment_mine_gwnum);
        imgRed = (ImageView) viewLayout.findViewById(R.id.fragmeng_mine_img_red);
        mycollection = (TextView) viewLayout.findViewById(R.id.fragment_mine_scnum);
        userImageBg = (ImageView) viewLayout.findViewById(R.id.userImageBg);
        im_kefu = (ImageView) viewLayout.findViewById(R.id.fragment_mine_kefu);
        im_tousu = (ImageView) viewLayout.findViewById(R.id.fragment_imtousu);
        im_fxapp = (ImageView) viewLayout.findViewById(R.id.fragment_fxapp);
        im_help = (ImageView) viewLayout.findViewById(R.id.fragment_helpcenter);
        iv_message_min= (ImageView) viewLayout.findViewById(R.id.iv_message_min);
        dianpushuliang = (TextView) viewLayout.findViewById(R.id.imageView5);
        fragment_mine_username = (TextView) viewLayout.findViewById(R.id.fragment_mine_username);
        rl_setmessage= (RelativeLayout) viewLayout.findViewById(R.id.rl_setmessage);

        iv_message_min.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isLogin(getActivity(), true)) {
                    return;
                }
                Intent intent=new Intent(getActivity(), MessageActivity.class);
                startActivity(intent);
            }
        });
//        ll_jinbi = (LinearLayout) viewLayout.findViewById(R.id.mine_huijinbi);
//        ll_yumoney = (LinearLayout) viewLayout.findViewById(R.id.mine_yumoney);
//        tv_zhanghuyue = (TextView) viewLayout.findViewById(R.id.mine_zhanghuyue);
        fragment_mine_gwnum= (TextView) viewLayout.findViewById(R.id.fragment_mine_gwnum);
        textView7= (TextView) viewLayout.findViewById(R.id.textView7);
        if(SPUtils.getInstance().getString(SPConstants.KEY_ISSTORE).equals("1")){
            dianpushuliang.setText("1");
        }else{
            dianpushuliang.setText("0");
        }
        dianpushuliang.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Intent intent = new Intent()
                try {
                    if (getActivity() instanceof MainFragment) {
                        MainFragment mainFragment = (MainFragment) getActivity();
                        mainFragment.bottomTabBar.setSelectItem("店铺");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        textView7.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Intent intent = new Intent()
                try {
                    if (getActivity() instanceof MainFragment) {
                        MainFragment mainFragment = (MainFragment) getActivity();
                        mainFragment.bottomTabBar.setSelectItem("店铺");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });
//if(fragment_mine_username.getText().toString().equals("登录/注册")){
//    dianpushuliang.setText("0");
//    Intent intent=new Intent(getActivity(),LoginActivity.class);
//    startActivity(intent);
//
//}else {

        Longing.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!isLogin(getActivity(), true)) {
                return;
            }
            if(TvuserNickname.getText().toString().equals("登录/注册")){
                rl_setmessage.setVisibility(View.GONE);
                mess_yuan.setVisibility(View.GONE);
                rl_setmessage.setVisibility(View.GONE);
                dianpushuliang.setText("0");
                Intent intent = new Intent(getActivity(), LoginActivity.class);
                startActivity(intent);
            }else{
                Intent intent = new Intent(getActivity(), PersonalProfileActivity.class);
                startActivity(intent);
            }
        }
    });
//        TvuserNickname.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (!isLogin(getActivity(), true)) {
//                    return;
//                }
//                if(TvuserNickname.getText().toString().equals("登录/注册")){
//                    mess_yuan.setVisibility(View.GONE);
//                    dianpushuliang.setText("0");
//                    Intent intent = new Intent(getActivity(), LoginActivity.class);
//                    startActivity(intent);
//                }else{
//                    Intent intent = new Intent(getActivity(), PersonalProfileActivity.class);
//                    startActivity(intent);
//                }
//            }
//        });

//}

        fragment_mine_gwnum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isLogin(getActivity(), true)) {
                    return;
                }
                Intent intent=new Intent(getActivity(),ShopCartActivity.class);
                startActivity(intent);
            }
        });
        iv_fragment_mine_yaoqing= (ImageView) viewLayout.findViewById(R.id.iv_fragment_mine_yaoqing);
        iv_fragment_mine_yaoqing.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isLogin(getActivity(), true)) {
                    return;
                }
                Intent intent=new Intent(getActivity(),InvitationVIPActivity.class);
                startActivity(intent);
            }
        });
        mycollection.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!isLogin(getActivity(), true)) {
                    return;
                }
                Intent intent = new Intent(getActivity(),MyCollectActivity.class);
                startActivity(intent);
            }
        });

        ImageSet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!isLogin(getActivity(), true)) {
                    return;
                }
                Intent intent = new Intent(getActivity(),PersonSetActivity.class);
                startActivity(intent);
            }
        });
        Immediatecash.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!isLogin(getActivity(), true)) {
                    return;
                }
                Intent intent = new Intent(getActivity(),DepositActivity.class);
                startActivity(intent);
            }
        });


        LinearMyOrder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!isLogin(getActivity(), true)) {
                    return;
                }
                Intent intent = new Intent(getActivity(),AllOrderActivity.class);
                startActivity(intent);
            }
        });
        ImaPending.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!isLogin(getActivity(), true)) {
                    return;
                }
                Intent intent = new Intent(getActivity(),AllOrderActivity.class);
                intent.putExtra("roomid",1);
                startActivity(intent);
            }
        });
        ImaLivery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (!isLogin(getActivity(), true)) {
                    return;
                }
                Intent intent = new Intent(getActivity(),AllOrderActivity.class);
                intent.putExtra("roomid",2);
                startActivity(intent);



            }
        });
        ImaGoodreceive.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (!isLogin(getActivity(), true)) {
                    return;
                }
                Intent intent = new Intent(getActivity(),AllOrderActivity.class);
                intent.putExtra("roomid",3);
                startActivity(intent);

            }
        });
        ImaPendcomm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!isLogin(getActivity(), true)) {
                    return;
                }
                Intent intent = new Intent(getActivity(),AllOrderActivity.class);
                intent.putExtra("roomid",4);
                startActivity(intent);

            }
        });
        imagereturnafter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!isLogin(getActivity(), true)) {
                    return;
                }
                Intent intent = new Intent(getActivity(),ReturnafterActivity.class);
                startActivity(intent);
            }
        });

        imgRed.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!isLogin(getActivity(), true)) {
                    return;
                }
                Intent intent = new Intent(getActivity(),RedbagActivity.class);
                startActivity(intent);
            }
        });

        im_kefu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!isLogin(getActivity(), true)) {
                    return;
                }
                Intent intent = new Intent(getActivity(), com.huifaapp.mall.activity.Homefragment.WebActivity.class);
                intent.putExtra("url",ApiManager.KEFU);
                startActivity(intent);
            }
        });
        im_fxapp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!isLogin(getActivity(), true)) {
                    return;
                }
                Intent intent = new Intent(getActivity(), OneShareActivity.class);
                startActivity(intent);
            }
        });
        im_tousu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!isLogin(getActivity(), true)) {
                    return;
                }
                Intent intent = new Intent(getActivity(), ComplaintActivity.class);
                startActivity(intent);
            }
        });
        im_help.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!isLogin(getActivity(), true)) {
                    return;
                }
                Intent intent = new Intent(getActivity(), HelpcenterActivity.class);
                startActivity(intent);
            }
        });
    }


    /**
     * 检查用户是否登录
     * @param context
     * @param isNeedToLoginView true 表示需要跳转登录界面   false 只检查用户是否登录
     * @return
     */
    public static boolean isLogin(Context context, boolean isNeedToLoginView){
        String token =  SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN);

        if (!TextUtils.isEmpty(token)){
            return true;
        }
        if (isNeedToLoginView) {
            Intent intent = new Intent(context,LoginActivity.class);
            context.startActivity(intent);
            return false;
        }
        return false;
    }

    public static void changeLight(ImageView v, int brightness) {

        ColorMatrix cMatrix = new ColorMatrix();

        cMatrix.set(new float[] { 1, 0, 0, 0, brightness, 0, 1, 0, 0,
                brightness, 0, 0, 1, 0, brightness, 0, 0, 0, 1, 0 });

        v.setColorFilter(new ColorMatrixColorFilter(cMatrix));
    }

}
